//
//  InvoiceViewController.m
//  云律司
//
//  Created by 韦淋 on 2017/7/3.
//  Copyright © 2017年 test. All rights reserved.
//

#import "InvoiceViewController.h"


@interface InvoiceViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIButton *barAddButton;
@property (nonatomic, strong) UITableView *invoiceTablewView;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) NSArray *caseNumArr;

@end

@implementation InvoiceViewController
- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = false;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.dataSource = [NSArray array];
    self.caseNumArr = [NSArray array];
    self.barTitleLable.text = @"开具列表 ";self.view.backgroundColor = [UIColor whiteColor];
    [self initUI];
    [self getData];
}
- (void)initUI{
    [self.view addSubview:self.invoiceTablewView];
    [self.view insertSubview:self.barAddButton aboveSubview:self.barView];
}
- (void)getData{
    
    
    // 创建信号量
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    // 创建全局并行
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        
        // 请求一
        [NetworkingManager getUrl:[NSString stringWithFormat:@"%@create_id=%@",INVOICE_URL,[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"]] dic:nil Succeed:^(id responseData) {
            self.dataSource = responseData[@"result"];
            NSLog(@"success:%@",self.dataSource);
            dispatch_semaphore_signal(semaphore);
        } failure:^(NSError *error) {
            NSLog(@"error:%@",error);
            [MBProgressHUD showError:@"网络错误"];
            dispatch_semaphore_signal(semaphore);
        }];
        
        
    });
    dispatch_group_async(group, queue, ^{
        
        // 请求二
        [NetworkingManager getUrl:[NSString stringWithFormat:@"%@company_id=%@",INVOICECASENUM_URL,[InfoSingleTon personInfoSingleTon].infoDic[@"cid"]] dic:nil Succeed:^(id responseData) {
            self.caseNumArr = responseData[@"result"];
            NSLog(@"success1:%@",responseData);
            dispatch_semaphore_signal(semaphore);
        } failure:^(NSError *error) {
            NSLog(@"error1:%@",error);
            [MBProgressHUD showError:@"网络错误"];
            dispatch_semaphore_signal(semaphore);
        }];
        
    });
    
    dispatch_group_notify(group, queue, ^{
        
        // 三个请求对应三次信号等待
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        //在这里 进行请求后的方法，回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //更新UI操作
            NSLog(@"wancheng");
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self.invoiceTablewView.mj_header endRefreshing];
            [self.invoiceTablewView reloadData];
        });
    });


    
}
#pragma mark - Button Target
- (void)action_AddButton:(UIButton *)sender{
    AddInvoiceViewController *AIVC = [[AddInvoiceViewController alloc] init];
    AIVC.caseNumArray = self.caseNumArr;
    [self.navigationController pushViewController:AIVC animated:YES];
}
#pragma mark - Method
- (void)loadNewData{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.dataSource = nil;
        [self getData];
    });
    
    
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 165;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    InvoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InvoiceCell" forIndexPath:indexPath];
    cell.caseNumber.text = [NSString stringWithFormat:@"案          号： %@",self.dataSource[indexPath.row][@"ah_num"]];
    cell.proposerLable.text = [NSString stringWithFormat:@"申   请   人： %@",self.dataSource[indexPath.row][@"sqr"]];
    cell.invoiceTitle.text = [NSString stringWithFormat:@"发 票 抬 头： %@",self.dataSource[indexPath.row][@"fptt"]];
    cell.invoiceAmount.text = [NSString stringWithFormat:@"开 票 金 额： %@",self.dataSource[indexPath.row][@"kpje"]];
    cell.invoiceDate.text = [NSString stringWithFormat:@"开 票 时 间： %@",self.dataSource[indexPath.row][@"kprq"]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    InvoiceDetailViewController *IDVC = [[InvoiceDetailViewController alloc] init];
    IDVC.caseNumArray = self.caseNumArr;
    IDVC.InvoiceDetailDic = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:IDVC animated:YES];
}
#pragma mark - Getter
- (UIButton *)barAddButton{
    if (!_barAddButton) {
        _barAddButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _barAddButton.frame = CGRectMake(330, 25, 30, 30);
        [_barAddButton setBackgroundImage:[UIImage imageNamed:@"jiahao"] forState:UIControlStateNormal];
        [_barAddButton addTarget:self action:@selector(action_AddButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _barAddButton;
}
- (UITableView *)invoiceTablewView{
    if (!_invoiceTablewView) {
        _invoiceTablewView = [[UITableView alloc] initWithFrame:CGRectMake(0, 80, self.view.bounds.size.width, self.view.bounds.size.height - 80) style:UITableViewStylePlain];
        _invoiceTablewView.backgroundColor = [UIColor clearColor];
        _invoiceTablewView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _invoiceTablewView.delegate = self;
        _invoiceTablewView.dataSource = self;
        _invoiceTablewView.estimatedRowHeight = 180;
        [_invoiceTablewView registerClass:[InvoiceCell class] forCellReuseIdentifier:@"InvoiceCell"];
        //下拉刷新
        
        NSMutableArray *images = [NSMutableArray array];//图片
        for (int i = 1; i < 48; i++) {//假设50张图片
            [images addObject:[UIImage imageNamed:[NSString stringWithFormat:@"%zd",i]]];
        }
        MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        //        header.frame = CGRectMake(0, 0, SCREEN_WIDTH, 50);
        //        [header setImages:images forState:MJRefreshStateRefreshing];// 设置正在刷新状态的动画图片
        
        // 设置普通状态的动画图片
        [header setImages:@[images[0]] forState:MJRefreshStateIdle];
        // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
        [header setImages:@[images[0]] forState:MJRefreshStatePulling];
        // 设置正在刷新状态的动画图片
        [header setImages:images forState:MJRefreshStateRefreshing];
        _invoiceTablewView.mj_header = header;// 设置header
        header.lastUpdatedTimeLabel.hidden = YES;// 隐藏时间
        header.stateLabel.hidden = YES;// 隐藏状态
        
    }
    return _invoiceTablewView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
